package com.lingjtx.order.service.impl;

import com.lingjtx.common.core.algorithm.RSAUtil;
import com.lingjtx.common.pay.PayCenter;
import com.lingjtx.common.pay.common.PayChannelEnum;
import com.lingjtx.common.pay.model.NotifyEntity;
import com.lingjtx.common.pay.util.WePaySignatureUtil;
import com.lingjtx.order.service.NotifyService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
@RequiredArgsConstructor
public class NotifyServiceImpl implements NotifyService {

    @Value("${pay.wepay.priKey}")
    private String priKey;

    @Value("${pay.wepay.notifyUrl}")
    private String wxNotifyUrl;

    private final PayCenter payCenter;

    @Override
    public void wepayNotify(String body, String signature, String timestamp, String nonce) {
        // 构建待签名消息
        String message = WePaySignatureUtil.buildMessage("POST", wxNotifyUrl, timestamp, nonce, body);
        // 生成签名
        String sign = RSAUtil.sign(message, priKey);

        // 检查是否微信支付平台发送来的消息，防止被攻击
        if (signature.equals(sign)) {
            NotifyEntity notify = payCenter.callbackNotify(PayChannelEnum.WECHAT, body);
            if (Objects.nonNull(notify)) {
                switch (notify.getNotifyType()) {
                    case REFUND -> handleRefund(notify);
                    case TRANSACTION -> handleTransaction(notify);
                }
            }
        }
    }

    // 交易通知回调
    public void handleTransaction(NotifyEntity notify) {
        // 插入一条支付信息

        // 修改订单状态

        // 减库存
    }

    // 退款通知回调
    public void handleRefund(NotifyEntity notify) {
        // 插入一条退款记录
    }
}
